package com.zhangmeng.tools.config;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.io.resource.Resource;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.media.Media;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author : 芊芊墨客
 * @version : 1.0
 * @date : 2023-04-24 12:01
 */
public class MusicFileConfig {

    public static ObservableList<File> dirs = FXCollections.observableArrayList();
    public static ObservableList<Media> medias = FXCollections.observableArrayList();
    public static ObservableList<File> files = FXCollections.observableArrayList();

    public static void init(){
        files = getMusicFiles();
        medias = getMusicMedias();
    }

    public static String config_path() {
        Resource resource = new ClassPathResource("music.properties");
        InputStream inputStream = resource.getStream();
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties.getProperty("base.music.path");
    }

    public static ObservableList<File> getDirsList() {
        String dir = config_path();
        File file = new File(dir);
        if (file.exists() && file.isDirectory()) {
            dirs.add(file);
        }
        return dirs;
    }

    public static ObservableList<File> getMusicFiles() {
        if (files.size() == 0) {
            getDirsList().forEach((dir) -> {
                if (dir.exists()) {
                    File[] mfiles = dir.listFiles(new FilenameFilter() {
                        public boolean accept(File dir, String name) {
                            return name.endsWith("mp3");
                        }
                    });
                    files.addAll(mfiles);
                }
            });
            return files;
        } else {
            return files;
        }
    }

    public static ObservableList<Media> getMusicMedias() {
        if (medias.size() == 0) {
            getDirsList().forEach((dir) -> {
                if (dir.exists()) {
                    File[] files = dir.listFiles(new FilenameFilter() {
                        public boolean accept(File dir, String name) {
                            return name.endsWith("mp3");
                        }
                    });
                    for (File file : files) {
                        String uri = file.toURI().toASCIIString();
                        Media media = new Media(uri);
                        medias.add(media);
                    }
                }
            });
            return medias;
        } else {
            return medias;
        }
    }
}
